#include "Script.h"

LuaScript::LuaInterface* Luna<LuaScript::LuaInterface>::m_mine=NULL;
const char LuaScript::LuaInterface::className[] = "LuaInterface";
const Luna<LuaScript::LuaInterface>::RegType LuaScript::LuaInterface::Register[] = {
	{ "LoadModel",  &LuaScript::LuaInterface::LoadModel },
	{ "AddRenderObject", &LuaScript::LuaInterface::AddRenderObject },
	{ 0 }
};

int LuaScript::LuaInterface::LoadModel(lua_State* L)
{
	assert(m_parent);
	string modelName(lua_tostring(L,-1));
	if(modelName!="")
	{
		m_parent->SendMessage(MSG_LOAD_MODEL,AuxGroupArgus(modelName));
	}
	lua_pop(L,1);
	return 0;
}
/*
int LuaScript::LuaInterface::LoadMesh(lua_State* L)
{
	assert(m_parent);
	string meshName(lua_tostring(L,-1));
	cout<<meshName<<endl;
	m_parent->SendMessage(MSG_LOAD_MODEL,AuxGroupArgus(meshName));
	lua_pop(L,1);
	return 0;
}*/

int LuaScript::LuaInterface::AddRenderObject(lua_State* L)
{
	assert(m_parent);
	return 0;
}

Script::Script(string s)
	:Component(COMP_SCRIPT),
	m_scriptName(s)
{
}

Script::~Script(void)
{
}

LuaScript::LuaScript(string s )
	:Script(s),
	m_scriptPath("")
{
}

LuaScript::~LuaScript()
{
	if(m_lua)
	{
		lua_close(m_lua);
		m_lua=0;
	}
}

void LuaScript::AddedToObject()
{
	RequestMessage(MSG_RUN_SCRIPT,&LuaScript::RunScript);
	RequestMessage(MSG_INITIAL_LOGIC,&LuaScript::Initial);
}

void LuaScript::Initial(const Message& msg)
{

	//Resource::sPtr res;
	//SendMessage(MSG_GET_RESOURCE,AuxGroupArgus(m_scriptName,Resource::MEMORY,&res));
	SendMessage(MSG_GET_PATH,AuxGroupArgus(m_scriptName,&m_scriptPath));
	
	if(m_scriptPath=="")
		EXCEPTION("")
	m_lua= lua_open();   /* opens Lua */

	InitialCallBackClass();
	InitialLibrary();
	
	if (luaL_loadfile(m_lua, m_scriptPath.c_str()) || lua_pcall(m_lua, 0, 0, 0))
	{
		const char* err=lua_tostring(m_lua,-1);
		EXCEPTION(err);
	}
	
	if(Luna<LuaScript::LuaInterface>::m_mine!=NULL)
	{
		Luna<LuaScript::LuaInterface>::m_mine->SetParent(this);
	}
}

void LuaScript::InitialCallBackClass()
{
	Luna<LuaScript::LuaInterface>::Register(m_lua);
}

void LuaScript::InitialLibrary()
{
	luaopen_base(m_lua);             /* opens the basic library */
	luaopen_table(m_lua);            /* opens the table library */
	luaopen_string(m_lua);           /* opens the string lib. */
	luaopen_math(m_lua);             /* opens the math lib. */
}

void LuaScript::RunScript(const Message& msg)
{
	string functionName;
	AuxUnGroupArgus(msg.p,functionName);
	lua_getglobal(m_lua,functionName.c_str());
	if (lua_pcall(m_lua, 0, 0, 0) != 0)
	{
		const char* err=lua_tostring(m_lua, -1);
		cout<<err<<endl;
		EXCEPTION("Run lua script error");
	}
}